#include "ChangeTileAction.hpp"

ChangeTileAction::ChangeTileAction(Map* map, int layer, int setTile, int tilex, int tiley, char* name){
    desc = "Set (" + StringHelper::itos(tilex) + "," + StringHelper::itos(tiley) + ")(" + StringHelper::itos(layer) + ") to " + name;
    value = setTile;
    target = map;
    targetLayer = layer;
    targetX = tilex;
    targetY = tiley;

    perform();
}

void ChangeTileAction::perform(){
    resizeResult = 0;
    needsResize = MapResizer::needsResize(target, targetX, targetY);
    if(needsResize)
        originalValue = NO_SPRITE;
    else
        originalValue = target->tiles[targetY*target->width + targetX][targetLayer];

    if(needsResize){
        sf::Rect<int> resizeArea;
        resizeArea.left = targetX;
        resizeArea.top = targetY;
        resizeArea.height = resizeArea.width = 1;
        resizeResult = MapResizer::resizeByMarquee(target, &resizeArea);
        target->tiles[(resizeResult->shiftY + targetY)*target->width + (targetX + resizeResult->shiftX)][targetLayer] = value;
    }else
        target->tiles[targetY*target->width + targetX][targetLayer] = value;
}

void ChangeTileAction::undo(){
    if(resizeResult != 0){
        MapResizer::shrink(target, resizeResult);
        delete resizeResult;
        resizeResult = 0;
    }
    if(!needsResize)
        target->tiles[targetY*target->width + targetX][targetLayer] = originalValue;
}

ChangeTileAction::~ChangeTileAction(){
    if(resizeResult != 0){
        delete resizeResult;
        resizeResult = 0;
    }
}